package com.qf.interceptor;

import com.qf.utils.APICounts;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * 注意，写完拦截器后，需要配置拦截器拦截哪些请求 的 uri路径
 */
@Component // 让spring框架启动时创建这个拦截器的对象
public class ApiContInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("========================"+request.getRequestURI());

        //1. 获取请求的 uri路径
        String requestURI = request.getRequestURI();

        //2. 修改map中的对应的uri的计数
        HashMap<String, Integer> apicountMap = APICounts.apicountMap;
        Integer integer = apicountMap.get(requestURI);
        int counts = integer == null ? 1 : integer + 1;
        apicountMap.put(requestURI,counts);

        return true; // 请求可以继续调用后面的controller中的方法；如果返回false，那么请求到此位置
    }
}
